package com.xingfly.web.api;

import com.xingfly.authentication.annotation.Authorization;
import com.xingfly.authentication.annotation.Me;
import com.xingfly.constant.ApiConstant;
import com.xingfly.constant.ErrorConstant;
import com.xingfly.constant.HttpStatus;
import com.xingfly.constant.Type;
import com.xingfly.error.TipException;
import com.xingfly.model.Count;
import com.xingfly.model.Event;
import com.xingfly.model.User;
import com.xingfly.model.dto.CountDTO;
import com.xingfly.model.vo.UserVO;
import com.xingfly.service.CommentService;
import com.xingfly.service.CountService;
import com.xingfly.service.EventService;
import com.xingfly.web.model.ResponseModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created by SuperS on 24/05/2017.
 *
 * @author SuperS
 */
@Api(value = "counts", description = "用户点赞、计数相关")
@RestController
@RequestMapping("/api/counts")
public class CountController {
    @Autowired
    private CountService countService;
    @Autowired
    private EventService eventService;
    @Autowired
    private CommentService commentService;

    @ApiOperation(value = "点赞操作", notes = "验证后实现点赞操作")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", value = ApiConstant.AUTHORIZATION, paramType = "header", dataType = "String", required = true),
            @ApiImplicitParam(name = "countDTO", value = "count传输对象", dataType = "CountDTO", required = true)
    })
    @Transactional
    @Authorization
    @PostMapping
    public ResponseModel like(@ApiIgnore @Me User me, @RequestBody CountDTO countDTO) throws TipException {
        if (countDTO.getObjId() == null || countDTO.getObjType() == null) {

        }
        //根据数据传输对象 中的 id和 type 查询需要点赞的事件是否存在
        Event event = eventService.findByObjIdAndType(countDTO.getObjId(), countDTO.getObjType());
        if (event == null) {
            throw new TipException(ErrorConstant.ERROR_MSG_ARGUMENT_NOT_NULL, ErrorConstant.ERROR_CODE_ARGUMENT_NOT_NULL);
        }
        if (countDTO.getObjId() == null || countDTO.getObjType() == null) {
            throw new TipException(ErrorConstant.ERROR_MSG_EVENT_NOT_FOUND, ErrorConstant.ERROR_CODE_EVENT_NOT_FOUND);
        }
        //判断是否已经点赞
        if (countService.isLike(event.getId(), me.getId())) {
            throw new TipException(ErrorConstant.ERROR_MSG_ERROR_OPTION, ErrorConstant.ERROR_CODE_ERROR_OPTION);
        }
        //根据event事件查询是否有相关的 count对象
        Count count = countService.findByEventId(event.getId());
        //没有人点过赞、当前用户时第一个点赞
        if (count == null) {
            //创建count对象
            count = new Count();
            count.setCount(1L);
            count.setType(Type.COUNT_LIKE);
            count.setEvent(eventService.findByEventId(event.getId()));
            count.setUsers(Collections.singletonList(me));
        } else {
            //有人已经点过赞 那么 在其基础上+1
            Long num = count.getCount() + 1;
            List<User> users = count.getUsers();
            //将当前用户添加到点赞用户列表中
            users.add(me);
            count.setUsers(users);
            count.setCount(num);
        }
        //保存此对象
        countService.save(count);
        return ResponseModel.builder().message(HttpStatus.STATUS_INFO_CREATED).code(HttpStatus.STATUS_CODE_CREATED).build();
    }

    @ApiOperation(value = "查询操作", notes = "查询点赞数或评论数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "Event ID", dataType = "Long", paramType = "path", required = true),
            @ApiImplicitParam(name = "type", value = "type 0(查询like数量),其他(查询comment数量),默认0", dataType = "Integer", paramType = "query")
    })
    @Transactional
    @GetMapping("{id}")
    public ResponseModel showCounts(@PathVariable("id") Long eid, @RequestParam(defaultValue = "0") Integer type) throws TipException {
        //判断要查询的事件是否存在
        if (eid == null ||
                eventService.findByEventId(eid) == null) {
            throw new TipException(ErrorConstant.ERROR_MSG_EVENT_NOT_FOUND, ErrorConstant.ERROR_CODE_EVENT_NOT_FOUND);
        }
        Long count = null;
        switch (type) {
            //查询点赞数量
            case 0:
                Count c = countService.findByEventId(eid);
                if (c == null) {
                    count = 0L;
                } else {
                    count = c.getCount();
                }
                break;
            //查询评论数量
            default:
                count = commentService.countCommentsByEventId(eid);
                break;
        }
        return ResponseModel.builder().code(HttpStatus.STATUS_CODE_SUCCESS).message(HttpStatus.STATUS_INFO_SUCCESS).data(count).build();
    }

    @GetMapping("{id}/users")
    @ApiOperation(value = "查询操作", notes = "查询like某个事件的所有用户")
    @ApiImplicitParam(name = "id", value = "Event ID", dataType = "Long", paramType = "path", required = true)
    public ResponseModel showLikeUsers(@PathVariable("id") Long eid) throws TipException {
        if (eid == null ||
                eventService.findByEventId(eid) == null) {
            throw new TipException(ErrorConstant.ERROR_MSG_EVENT_NOT_FOUND, ErrorConstant.ERROR_CODE_EVENT_NOT_FOUND);
        }
        List<User> users = countService.findByEventId(eid).getUsers();

        List<UserVO> userVOS = new ArrayList<>();
        if (users != null) {
            for (User u : users) {
                userVOS.add(UserVO.toVO(u));
            }
        }
        return ResponseModel.builder().code(HttpStatus.STATUS_CODE_SUCCESS).message(HttpStatus.STATUS_INFO_SUCCESS).data(userVOS).build();
    }
}
